package com.dalianpai.gulimall.gulimallauthserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dalianpai.common.constant.AuthServerConstant;
import com.dalianpai.common.to.SocialUser;
import com.dalianpai.common.utils.HttpUtils;
import com.dalianpai.common.utils.R;
import com.dalianpai.common.vo.MemberRespVo;
import com.dalianpai.gulimall.gulimallauthserver.feign.MemberFeignService;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author WGR
 * @create 2020/7/16 -- 17:06
 */
@Controller
public class Oauth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession httpSession) throws Exception {
        System.out.println(code);
        Map<String, String> map = new HashMap<>();
        map.put("client_id","31031789");
        map.put("client_secret","38c9571dd37d99d7f3d6aab02a77d14d");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), new HashMap<>(), map);
        System.out.println(response);
        //2.处理
        if(response.getStatusLine().getStatusCode()==200){
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            R oauthLogin = memberFeignService.oauthLogin(socialUser);
            if(oauthLogin.getCode() == 0){
                MemberRespVo data = oauthLogin.getData("data", new TypeReference<MemberRespVo>() {
                });
                System.out.println("登录成功"+data);
                httpSession.setAttribute(AuthServerConstant.LOGIN_USER,data);
                return "redirect:http://gulimall.com";
            }else{
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else{
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }
}
